package me.work.pay.jsyl.mvp.presenter;

import android.app.Application;
import android.util.Log;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.work.pay.jsyl.app.Constants;
import me.work.pay.jsyl.app.utils.RxUtil;
import me.work.pay.jsyl.mvp.contract.GroupListContract;
import me.work.pay.jsyl.mvp.model.AppModel;
import me.work.pay.jsyl.mvp.model.entity.LauncherData;
import me.work.pay.jsyl.mvp.model.entity.UpdateInfo;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 10/28/2019 13:20
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class GroupListPresenter extends BasePresenter<GroupListContract.Model, GroupListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public GroupListPresenter(GroupListContract.Model model, GroupListContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getGroup() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("sn", Constants.sn);
        Observable.just(1).subscribeOn(Schedulers.io())
                .flatMap(new Function<Integer, ObservableSource<LauncherData>>() {
                    @Override
                    public ObservableSource<LauncherData> apply(Integer integer) throws Exception {
                        return mModel.getGroup(map, NetworkUtils.isConnected());
                    }
                })
                .compose(RxUtil.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<LauncherData>(mErrorHandler) {
                    @Override
                    public void onNext(LauncherData commonData) {
                        if (commonData.isLandscape() && ScreenUtils.isPortrait()) {
                            mRootView.requestScreenOrientation();
                        }
                        mRootView.update(commonData);
                        AppModel.getInstance().saveLauncherData(commonData);
                    }

                    @Override
                    public void onError(Throwable t) {
                        mRootView.update(new LauncherData());
                    }
                });
    }

    public void upload_log(String data) {
        /**
         * project：日志项目project名称
         * 	logstore：日志上传至的logstore名称
         * 	topic：日志topic，自定义。
         * 	source：日志来源，包括：arf_a8：阿尔丰A8设备；plugin：萤火虫插件等，使用前，由我们定义
         * 	data：日志数据，格式自定义，数据查询主要内容
         * 响应参数：
         * 	result_code：响应结果：success：上传成功；fail：上传失败
         * 	error_msg：失败原因。
         * */
        Map<String, Object> map = new HashMap<>();
        map.put("data", Constants.sn+","+data);
        map.put("project", "main-server-41");
        map.put("topic", Constants.sn);
        map.put("source", "arf_a8");
        map.put("logstore", "device");
        mModel.upload_log(map)
                .compose(RxUtil.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onNext(String data) {
                        Log.i("ArmsHttpLog", data);
                    }

                    @Override
                    public void onError(Throwable t) {
                        Log.e("ArmsHttpLog", t.toString());
                    }
                });
    }

    /**
     * 检查更新
     * */
    public void check_version() {
        mModel.check_version(AppUtils.getAppVersionName())
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<UpdateInfo>(mErrorHandler) {
                    @Override
                    public void onNext(UpdateInfo result) {
//                        if (result.code==0) {
                            mRootView.check_version(result);
//                        } else {
//                            mRootView.showMessage(result.getMsg());
//                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });

    }
}
